/*
* Copyright (c) 2007 by Kirill Kolodyazhniy.
* See the file "license.terms" for information on usage and redistribution.
*/

#ifndef M_SINGLETON_H
#define M_SINGLETON_H

#include "synchronize.h"
#include "mutex.h"

#include "exception.h"

namespace Engine
{
	/**
	*   Base class for singleton objects.
	*/
	template<class T>
	class Singleton:  public SingleThreaded<Mutex>
	{
	public:
		/**
		*   Constructor.
		*/
		Singleton()
		{
			Lock lock;
			Assert(!m_singleton);
			m_singleton = static_cast< T* >( this );
		}

		/**
		*   Destructor.
		*/
		~Singleton( void )
		{
			Lock lock;
			Assert( m_singleton );
			m_singleton = 0;
		}

		/**
		*   Return reference to singleton object.
		*/
		static T& GetSingleton( void )
		{
			Lock lock;
			Assert( m_singleton );
			return ( *m_singleton );
		}

		/**
		*   Return pointer to singleton object.
		*/
		static T* GetSingletonPtr( void )
		{
			Lock lock;
			return m_singleton;
		}

	private:

		static T* m_singleton;
	};
}

#endif

